<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :width="width"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="tag-select-container">
      <!-- 标签选择区域 -->
      <div class="tag-selection-area">
        <h4>可选标签：</h4>
        <el-checkbox-group v-model="selectedTagIds" @change="handleTagChange">
          <!-- 文本标签 -->
          <div v-if="textTags.length > 0" class="tag-group">
            <span class="tag-group-title type-0">文本标签</span>
            <el-checkbox
              v-for="tag in textTags"
              :key="tag.id"
              :label="tag.id"
              :disabled="isTagSelected(tag.id)"
            >
              {{ tag.tagName }}
              <!-- <span class="tag-type-badge type-0">文本</span> -->
            </el-checkbox>
          </div>

          <!-- 数字标签 -->
          <div v-if="numericTags.length > 0" class="tag-group">
            <span class="tag-group-title type-1">数字标签</span>
            <el-checkbox
              v-for="tag in numericTags"
              :key="tag.id"
              :label="tag.id"
              :disabled="isTagSelected(tag.id)"
            >
              {{ tag.tagName }}
              <!-- <span class="tag-type-badge type-1">数字</span> -->
              <span v-if="tag.tagUnit" class="tag-unit">({{ tag.tagUnit }})</span>
            </el-checkbox>
          </div>

          <!-- 选择标签 -->
          <div v-if="optionTags.length > 0" class="tag-group">
            <span class="tag-group-title type-2">选择标签</span>
            <el-checkbox
              v-for="tag in optionTags"
              :key="tag.id"
              :label="tag.id"
              :disabled="isTagSelected(tag.id)"
            >
              {{ tag.tagName }}
              <!-- <span class="tag-type-badge type-2">选择</span> -->
            </el-checkbox>
          </div>

          <!-- 是否标签 -->
          <div v-if="booleanTags.length > 0" class="tag-group">
            <span class="tag-group-title type-3">是否标签</span>
            <el-checkbox
              v-for="tag in booleanTags"
              :key="tag.id"
              :label="tag.id"
              :disabled="isTagSelected(tag.id)"
            >
              {{ tag.tagName }}
              <!-- <span class="tag-type-badge type-3">是否</span> -->
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>

      <!-- 已选择的标签条件表格 -->
      <div class="tag-conditions-area">
        <h4>标签条件设置：</h4>
        <el-table :data="tagConditions" border style="width: 100%">
          <el-table-column prop="tagName" label="标签名称" width="150">
            <template slot-scope="scope">
              <span v-if="isFirstRowOfTag(scope.$index)">{{ scope.row.tagName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="operator" label="比较操作符" width="150">
            <template slot-scope="scope">
              <el-select 
                v-if="scope.row.tagType !== 3"
                v-model="scope.row.operator" 
                placeholder="选择操作符"
                @change="handleOperatorChange(scope.row)"
              >
                <el-option
                  v-for="opt in scope.row.availableOperators"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
              <span v-else class="no-operator">—</span>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="标签值">
            <template slot-scope="scope">
              <!-- 文本标签 -->
              <el-input
                v-if="scope.row.tagType === 0"
                v-model="scope.row.value"
                placeholder="请输入文本"
                clearable
              />
              <!-- 数字标签 -->
              <div v-else-if="scope.row.tagType === 1" class="numeric-input-container">
                <el-input-number
                  v-if="scope.row.operator !== 'range'"
                  v-model="scope.row.value"
                  :precision="0"
                  placeholder="请输入数字"
                  style="width: 100%"
                />
                <div v-else class="range-input-container">
                  <el-input-number
                    v-model="scope.row.value"
                    :precision="0"
                    placeholder="最小值"
                    style="width: 48%"
                  />
                  <span class="range-separator">至</span>
                  <el-input-number
                    v-model="scope.row.value2"
                    :precision="0"
                    placeholder="最大值"
                    style="width: 48%"
                  />
                </div>
                <span v-if="scope.row.tagUnit" class="value-unit">{{ scope.row.tagUnit }}</span>
              </div>
              <!-- 选择标签 -->
              <el-select
                v-else-if="scope.row.tagType === 2"
                v-model="scope.row.value"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="option in scope.row.tagOptions"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>
              <!-- 是否标签 -->
              <el-select
                v-else-if="scope.row.tagType === 3"
                v-model="scope.row.value"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="option in scope.row.tagOptions"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="scope">
              <el-button
                v-if="(scope.row.tagType === 0 || scope.row.tagType === 1) && isFirstRowOfTag(scope.$index)"
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="addTagCondition(scope.row)"
                style="margin-right: 5px;"
              />
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeTagCondition(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCompanyTagsQueryParam } from "@/api/biz/api";

export default {
  name: "TagSelect",
  props: {
    // 弹框是否显示
    visible: {
      type: Boolean,
      default: false
    },
    // 弹框标题
    title: {
      type: String,
      default: "选择企业标签"
    },
    // 弹框宽度
    width: {
      type: String,
      default: "80%"
    },
    // 已选择的标签条件（用于编辑模式）
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogVisible: false,
      textTags: [], // 文本标签列表
      numericTags: [], // 数字标签列表
      optionTags: [], // 选择标签列表
      booleanTags: [], // 是否标签列表
      textOperators: [], // 文本标签操作符
      numericOperators: [], // 数字标签操作符
      optionOperators: [], // 选择标签操作符
      tagConditions: [], // 标签条件列表
      selectedTagIds: [] // 已选择的标签ID
    };
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogVisible = newVal;
        if (newVal) {
          this.initDialog();
        }
      },
      immediate: true
    },
    dialogVisible(newVal) {
      this.$emit('update:visible', newVal);
    }
  },
  created() {
    // 组件创建时不立即加载标签，等弹框打开时再加载
  },
  methods: {
    // 加载标签数据
    loadTags() {
      return getCompanyTagsQueryParam().then(response => {
        if (response.code === 200) {
          const data = response.data || {};
          
          // 处理文本标签
          this.textTags = data.textTags?.tags || [];
          this.textOperators = this.mapOperators(data.textTags?.opts || []);
          
          // 处理数字标签
          this.numericTags = data.numericTags?.tags || [];
          this.numericOperators = this.mapOperators(data.numericTags?.opts || []);
          
          // 处理选择标签
          this.optionTags = data.optionTags?.tags || [];
          this.optionOperators = this.mapOperators(data.optionTags?.opts || []);
          
          // 处理是否标签
          this.booleanTags = data.booleanTags?.tags || [];
          
          console.log('获取标签列表成功:', response);
          return response;
        }
      }).catch(error => {
        console.error('获取标签列表失败:', error);
        this.textTags = [];
        this.numericTags = [];
        this.optionTags = [];
        this.booleanTags = [];
        return Promise.reject(error);
      });
    },
    // 映射操作符
    mapOperators(opts) {
      const operatorMap = {
        '等于': { value: 'eq', label: '等于' },
        '不等于': { value: 'ne', label: '不等于' },
        '大于': { value: 'gt', label: '大于' },
        '大于等于': { value: 'gte', label: '大于等于' },
        '小于': { value: 'lt', label: '小于' },
        '小于等于': { value: 'lte', label: '小于等于' },
        '左模糊': { value: 'leftLike', label: '左模糊' },
        '右模糊': { value: 'rightLike', label: '右模糊' },
        '左右模糊': { value: 'like', label: '左右模糊' },
        '区间': { value: 'range', label: '区间' }
      }; 
      return opts.map(opt => operatorMap[opt] || { value: opt, label: opt });
    },
    // 根据标签类型获取默认操作符列表
    getDefaultOperatorsByType(tagType) {
      if (tagType === 0) {
        // 文本标签：等于、不等于、左模糊、右模糊、左右模糊
        return [
          { value: 'eq', label: '等于' },
          { value: 'ne', label: '不等于' },
          { value: 'leftLike', label: '左模糊' },
          { value: 'rightLike', label: '右模糊' },
          { value: 'like', label: '左右模糊' }
        ];
      } else if (tagType === 1) {
        // 数字标签：等于、大于、大于等于、小于、小于等于、区间
        return [
          { value: 'eq', label: '等于' },
          { value: 'gt', label: '大于' },
          { value: 'gte', label: '大于等于' },
          { value: 'lt', label: '小于' },
          { value: 'lte', label: '小于等于' },
          { value: 'range', label: '区间' }
        ];
      } else if (tagType === 2) {
        // 选择标签：等于
        return [
          { value: 'eq', label: '等于' }
        ];
      } else {
        // 是否标签：没有操作符
        return [];
      }
    },
    // 初始化弹框
    initDialog() {
      this.selectedTagIds = [];
      this.tagConditions = [];
      
      // 加载标签数据
      this.loadTags().then(() => {
        // 如果有传入的value，则初始化已选择的条件
        if (this.value && this.value.length > 0) {
          this.initTagConditions(this.value);
        }
      });
    },
    // 初始化标签条件
    initTagConditions(value) {
      this.tagConditions = JSON.parse(JSON.stringify(value));
      // 为每个条件设置可用的操作符和选项
      this.tagConditions.forEach(condition => {
        const tag = this.findTagById(condition.tagId);
        if (tag) {
          condition.tagName = tag.tagName;
          condition.tagType = tag.tagType;
          condition.tagUnit = tag.tagUnit || '';
          condition.availableOperators = this.getAvailableOperators(tag.tagType);
          
          // 处理选择标签和是否标签的选项
          if ((tag.tagType === 2 || tag.tagType === 3) && tag.tagOptions) {
            condition.tagOptions = tag.tagOptions.split(',');
          }
          
          // 处理区间值
          if (tag.tagType === 1 && condition.operator === 'range' && condition.value2 === undefined) {
            condition.value2 = null;
          }
        }
      });
      this.selectedTagIds = this.tagConditions.map(condition => condition.tagId);
    },
    // 根据标签ID查找标签
    findTagById(tagId) {
      return [...this.textTags, ...this.numericTags, ...this.optionTags, ...this.booleanTags]
        .find(tag => tag.id === tagId);
    },
    // 根据标签类型获取可用的操作符
    getAvailableOperators(tagType) {
      // 优先使用从接口获取的操作符，如果没有则使用默认操作符
      if (tagType === 0) {
        return this.textOperators.length > 0 ? this.textOperators : this.getDefaultOperatorsByType(0);
      } else if (tagType === 1) {
        return this.numericOperators.length > 0 ? this.numericOperators : this.getDefaultOperatorsByType(1);
      } else if (tagType === 2) {
        return this.optionOperators.length > 0 ? this.optionOperators : this.getDefaultOperatorsByType(2);
      } else {
        return []; // 是否标签没有操作符
      }
    },
    // 标签选择变化
    handleTagChange(selectedIds) {
      // 找出新选择的标签（现在允许同一标签有多个条件，所以只检查是否至少有一个条件）
      const newSelectedIds = selectedIds.filter(id => 
        !this.tagConditions.some(condition => condition.tagId === id)
      );
      
      // 为每个新选择的标签添加到条件表格
      newSelectedIds.forEach(tagId => {
        const tag = this.findTagById(tagId);
        if (tag) {
          this.addTagConditionRow(tag);
        }
      });
      
      // 找出取消选择的标签（如果该标签的所有条件行都被删除，则从selectedTagIds中移除）
      const removedIds = this.selectedTagIds.filter(id => !selectedIds.includes(id));
      removedIds.forEach(tagId => {
        // 删除该标签的所有条件行
        this.tagConditions = this.tagConditions.filter(condition => condition.tagId !== tagId);
      });
    },
    // 添加标签条件行（内部方法）
    addTagConditionRow(tag) {
      const availableOperators = this.getAvailableOperators(tag.tagType);
      const defaultOperator = availableOperators.length > 0 ? availableOperators[0].value : '';
      
      // 处理是否标签和选择标签的选项
      let tagOptions = [];
      if ((tag.tagType === 2 || tag.tagType === 3) && tag.tagOptions) {
        tagOptions = tag.tagOptions.split(',');
      }
      
      this.tagConditions.push({
        tagId: tag.id,
        tagName: tag.tagName,
        tagType: tag.tagType,
        tagUnit: tag.tagUnit || '',
        tagOptions: tagOptions,
        availableOperators: availableOperators,
        operator: defaultOperator,
        value: tag.tagType === 3 ? (tagOptions.length > 0 ? tagOptions[0] : '') : '',
        value2: null // 用于区间输入
      });
    },
    // 添加同一标签的新条件行（用户点击添加按钮）
    addTagCondition(row) {
      const tag = this.findTagById(row.tagId);
      if (tag) {
        this.addTagConditionRow(tag);
      }
    },
    // 操作符变化处理
    handleOperatorChange(row) {
      // 如果从区间切换到其他操作符，清空value2
      if (row.operator !== 'range' && row.value2 !== null && row.value2 !== undefined) {
        row.value2 = null;
      }
      // 如果切换到区间，初始化value2
      if (row.operator === 'range' && (row.value2 === null || row.value2 === undefined)) {
        row.value2 = row.value || null;
      }
    },
    // 检查标签是否已选择
    isTagSelected(tagId) {
      // 现在允许同一标签有多个条件，所以只要有一个条件就认为已选择
      return this.tagConditions.some(condition => condition.tagId === tagId);
    },
    // 判断当前行是否是同一标签的第一行
    isFirstRowOfTag(index) {
      if (index === 0) {
        return true;
      }
      const currentTagId = this.tagConditions[index].tagId;
      const previousTagId = this.tagConditions[index - 1].tagId;
      return currentTagId !== previousTagId;
    },
    // 删除标签条件
    removeTagCondition(index) {
      // 先获取要删除的条件
      const removedCondition = this.tagConditions[index];
      // 删除条件
      this.tagConditions.splice(index, 1);
      // 检查该标签是否还有其他条件行，如果没有则从selectedTagIds中移除
      if (removedCondition) {
        const hasOtherConditions = this.tagConditions.some(condition => 
          condition.tagId === removedCondition.tagId
        );
        if (!hasOtherConditions) {
          const tagIndex = this.selectedTagIds.indexOf(removedCondition.tagId);
          if (tagIndex > -1) {
            this.selectedTagIds.splice(tagIndex, 1);
          }
        }
      }
    },
    // 获取操作符文本
    getOperatorText(operator) {
      const operatorMap = {
        'eq': '等于',
        'ne': '不等于',
        'gt': '大于',
        'gte': '大于等于',
        'lt': '小于',
        'lte': '小于等于',
        'leftLike': '左模糊',
        'rightLike': '右模糊',
        'like': '左右模糊',
        'range': '区间'
      };
      return operatorMap[operator] || operator;
    },
    // 取消
    handleCancel() {
      this.dialogVisible = false;
      this.$emit('cancel');
    },
    // 确定
    handleConfirm() {
      if (this.tagConditions.length === 0) {
        this.$modal.msgWarning('请至少选择一个标签条件');
        return;
      }
      
      // 验证所有条件是否填写完整
      for (let i = 0; i < this.tagConditions.length; i++) {
        const condition = this.tagConditions[i];
        
        // 是否标签不需要操作符
        if (condition.tagType !== 3 && !condition.operator) {
          this.$modal.msgWarning(`第${i + 1}行请选择比较操作符`);
          return;
        }
        
        // 验证值
        if (condition.tagType === 1 && condition.operator === 'range') {
          // 区间需要两个值
          if (condition.value === null || condition.value === undefined || 
              condition.value2 === null || condition.value2 === undefined) {
            this.$modal.msgWarning(`第${i + 1}行请填写完整的区间值`);
            return;
          }
          if (condition.value > condition.value2) {
            this.$modal.msgWarning(`第${i + 1}行区间最小值不能大于最大值`);
            return;
          }
        } else if (condition.tagType !== 3) {
          // 其他类型需要值
          if (condition.value === '' || condition.value === null || condition.value === undefined) {
            this.$modal.msgWarning(`第${i + 1}行请填写标签值`);
            return;
          }
        } else {
          // 是否标签需要选择值
          if (condition.value === '' || condition.value === null || condition.value === undefined) {
            this.$modal.msgWarning(`第${i + 1}行请选择标签值`);
            return;
          }
        }
      }
      
      // 生成显示文本
      const conditionTexts = this.tagConditions.map(condition => {
        let text = condition.tagName;
        
        if (condition.tagType !== 3) {
          const operatorText = this.getOperatorText(condition.operator);
          text += ` ${operatorText}`;
        }
        
        if (condition.tagType === 1 && condition.operator === 'range') {
          text += ` ${condition.value} 至 ${condition.value2}`;
        } else {
          text += ` ${condition.value}`;
        }
        
        if (condition.tagUnit) {
          text += condition.tagUnit;
        }
        
        return text;
      });
      
      // 构建返回的条件数据（按照新格式）
      const conditions = this.tagConditions.map(condition => {
        const result = {
          tagId: condition.tagId,
          tagType: condition.tagType === 3 ? 4 : condition.tagType, // 是否标签返回时tagType为4
          opt: condition.tagType === 3 ? '等于' : this.getOperatorText(condition.operator) || '', // 是否标签固定返回'等于'，其他转换为中文
          tagValue: ''
        };
        
        // 处理tagValue
        if (condition.tagType === 1 && condition.operator === 'range') {
          // 数字标签且为区间：使用三个下划线连接最小值和最大值
          result.tagValue = `${condition.value}___${condition.value2}`;
        } else {
          // 其他情况：直接使用value，转换为字符串
          result.tagValue = String(condition.value || '');
        }
        
        return result;
      });
      
      const result = {
        conditions: conditions,
        displayText: conditionTexts.join('; ')
      };
      console.log(' result =', result);
      this.dialogVisible = false;
      this.$emit('confirm', result);
    },
    // 关闭弹框
    handleClose() {
      this.$emit('close');
    }
  }
};
</script>

<style scoped>
.tag-select-container {
  max-height: 600px;
  overflow-y: auto;
}

.tag-selection-area {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.tag-selection-area h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.tag-group {
  margin-bottom: 10px;
}

.tag-group:last-child {
  margin-bottom: 0;
}

.tag-group-title {
  margin: 10px 10px 0px;
  padding:4px 8px;
  font-size: 12px;
  font-weight: 500;
  border-bottom: 1px solid #e4e7ed;
  border-radius: 3px;
  color: #fff;
}

.tag-conditions-area {
  margin-top: 20px;
}

.tag-conditions-area h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

/* .tag-type-badge {
  display: inline-block;
  padding: 2px 6px;
  margin-left: 8px;
  font-size: 11px;
  border-radius: 3px;
  color: #fff;
} */

.type-0 {
  background-color: #409eff;
}

.type-1 {
  background-color: #67c23a;
}

.type-2 {
  background-color: #e6a23c;
}

.type-3 {
  background-color: #f56c6c;
}

.tag-unit {
  margin-left: 4px;
  color: #909399;
  font-size: 12px;
}

.el-checkbox {
  margin-right: 15px;
  margin-bottom: 10px;
}

.numeric-input-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-input-container {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.range-separator {
  color: #909399;
  font-size: 12px;
  white-space: nowrap;
}

.value-unit {
  color: #909399;
  font-size: 12px;
  white-space: nowrap;
}

.no-operator {
  color: #909399;
  font-style: italic;
}

.dialog-footer {
  text-align: right;
}
</style>
